﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LeoShi.Soft.OpenSinaAPI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using TCS.DBUtility;
using TCS.Model.Weibo;
using System.Xml;
using LTP.Common;
using System.Data;
using System.Web.UI.HtmlControls;
using WeiBo.SinaAPI;

namespace TCS.Web.MembersHome
{
    public partial class WeiBoManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          if(!Page.IsPostBack)
          {
              if ((Session["BangShangMember"] != null) || (Session["BangShangMember"].ToString() != ""))
              {
                 
                  //BindRdoBtn();//绑定按钮
                  BindWeiBoList();
                 

              }
              else
              {
                  Response.Redirect("~/membersHome/login.aspx");
              }
          }
        }
        private void BindWeiBoList()
        {
                if (rdoIsMe.Checked == true)
                {
                    Session["WeiBoAPI"] = "http://api.t.sina.com.cn/statuses/user_timeline.json";//我发布的微博
                }

               if(rdoAllWeiBos.Checked)
               {
                   Session["WeiBoAPI"] = "http://api.t.sina.com.cn/statuses/friends_timeline.json";//我的微博和我关注人的微博
               }

                //{
                //    Session["WeiBoAPI"] = "http://api.t.sina.com.cn/statuses/friends_timeline.json";//我的微博和我关注人的微博
                //}
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            string url = Session["WeiBoAPI"].ToString();
            //WeiBo.SinaAPI.SinaBase.Comment = WeiBo.SinaAPI.UserController.WeiBoCommentControlle;
            string result = httpRequest.Request(url, String.Empty);
            List<Status> myWeiboList = JSONConvert.DeserializeJsonToListObjectStatus(result);
            List<Status> myWeiboList2 = new List<Status>();
            foreach (Status status in myWeiboList)
            {
                if(rdoAll.Checked)
                {
                    myWeiboList2 = myWeiboList;
                }
                if (rdoOrg.Checked)  //原创
                {
                    if (status.retweeted_status == null)
                    {
                         myWeiboList2.Add(status);
                       
                    }
                }
                if (rdoTurn.Checked)  //转发
                {
                    if (status.retweeted_status != null)
                    {
                        myWeiboList2.Add(status);

                    }
                }
                //if (rdoPic.Checked) //含图片
                //{
                //    if (status.original_pic != null)
                //    {
                //        myWeiboList2.Add(status);

                //    }
                //}
               
                if (status.in_reply_to_status_id == null)//没有回复
                {
                    
                }
                if (status.user.id == "123")
                {
                    ///id 是123的用户
                }
                if (status.user.verified == "false")
                {
                    //未认证用户
                }

            }
               resultCount.Text = myWeiboList2.Count.ToString();
                rptWeiboList.DataSource = myWeiboList2;
                rptWeiboList.DataBind();
        }
        protected void cbHeader_CheckedChanged(object sender, EventArgs e)
        {
            string itemId = "";
            foreach (RepeaterItem item in this.rptWeiboList.Items)
            {
                CheckBox cb = (CheckBox)item.FindControl("chkItem");
                if (cb.Checked == true)
                {
                    int ID = Convert.ToInt32(((HtmlInputHidden)item.FindControl("hfID")).Value);
                    // 微博删除
                    string delete = "http://api.t.sina.com.cn/statuses/destroy/:id.xml";
                    try
                    {
                        itemId = ID+",";
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    }
                    finally
                    {
                        
                    }
                }
            }

          
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (rdoIsMe.Checked)
            {
             //   ViewState["_searchkey"] = "page=" + lbtnNext.ToolTip + "&q=" + txtKey.Value;
                Session["WeiBoAPI"] = "http://api.t.sina.com.cn/statuses/user_timeline.json";//我发布的微博
            }
            if(rdoNotMe.Checked)
            {
                Session["WeiBoAPI"] = "http://api.t.sina.com.cn/statuses/friends_timeline.json";//我的微博和我关注人的微博
            }

            BindWeiBoList();
        }
        //
        protected void rptWeiboList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            //var url = "http://api.t.sina.com.cn/statuses/comment.xml"; //对微博进行评论

            string url = "http://api.t.sina.com.cn/statuses/repost.xml";  //微博转发

            //string text = ((TextBox)(e.Item.FindControl("txtContent"))).Text.ToString();
           string  text = "转发测试";
            //long id = long.Parse(((HiddenField)e.Item.FindControl("HidCommentID")).Value);
           long id = long.Parse(e.CommandArgument.ToString());
           string flag = Convert.ToString(e.CommandName.ToString());
            //转发
            if(flag=="zhuanfa")
            {
                httpRequest.Request(url, "status=" + HttpUtility.UrlEncode(text) + "&id=" + id);
             
            }
        }
        /// <summary>
        /// 微博管理批量转发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnGZ_Click(object sender, EventArgs e)
        {
            string itemId = "";
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;

            foreach (RepeaterItem item in this.rptWeiboList.Items)
            {
                CheckBox cb = (CheckBox)item.FindControl("chkItem");
                if (cb.Checked == true)
                {
                    long ID = Convert.ToInt64(((HtmlInputHidden)item.FindControl("hfID")).Value);
                    string url = "http://api.t.sina.com.cn/statuses/repost.xml";  //微博转发
                    string text = "";
                    try
                    {
                        httpRequest.Request(url, "status=" + HttpUtility.UrlEncode(text) + "&id=" + ID);
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    }
                    finally
                    {

                    }
                }
            }

        }
        /// <summary>
        /// 批量移除关注
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemoveAll_Click(object sender, EventArgs e)
        {
            string itemId = "";
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;

            foreach (RepeaterItem item in this.rptWeiboList.Items)
            {
                CheckBox cb = (CheckBox)item.FindControl("chkItem");
                if (cb.Checked == true)
                {
                    long UID = Convert.ToInt64(((HtmlInputHidden)item.FindControl("hfgz")).Value);
                    // 微博删除
                    string url = "http://api.t.sina.com.cn/friendships/destroy.xml";
                    try
                    {
                        string result = httpRequest.Request(url, "user_id=" + UID).ToString();
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    }
                    finally
                    {

                    }
                }
            }

        }
        //得到一条微博的部分评论
        private List<Comment> GetCommentByWbId(string id)
        {
                var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
             httpRequest.Token = Session["oauth_token"].ToString();
             httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
             httpRequest.UserRemoteIP = Request.UserHostAddress;
            string url = "http://api.t.sina.com.cn/statuses/comments.json?id="+id;
            string result = httpRequest.Request(url, string.Empty);
            List<Comment> listComment = JSONConvert.DeserializeJsonToListObjectComment(result);
            return listComment;
        }
        //根据微博id获取一条微博的转发数和评论数
        private StatusCount GetStatusCount(string id)
        {
              StatusCount  statusCount=null;
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            string url = "http://api.t.sina.com.cn/statuses/counts.json?ids="+id;
            string result = httpRequest.Request(url, string.Empty);
            List<StatusCount> statusCountList = JSONConvert.DeserializeJsonToListObjectStatusCount(result);
            if(statusCountList.Count==0||statusCountList==null)
            {
                 statusCount=null;
            }else
            {
               statusCount=statusCountList[0];
            }
           
            return statusCount;
        }
        public string SinaDateConvert(object obj)
        {
            string result = DateTime.Now.ToString();
            result = StringHelper.SinaDataConvert(obj.ToString());
            return result;
        }
        /// <summary>
        /// 批量评论内容不能重复&nbsp;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnComment_Click(object sender, EventArgs e)
        {
        
            string itemId = "";
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST) as HttpPost;
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            string a = "&nbsp;";//保持每次的内容不相同
            foreach (RepeaterItem item in this.rptWeiboList.Items)
            {
             
                CheckBox cb = (CheckBox)item.FindControl("chkItem");
                if (cb.Checked == true)
                {
                    a=a+a;
                    long ID = Convert.ToInt64(((HtmlInputHidden)item.FindControl("hfID")).Value);
                    // 微博删除
                    string url = "http://api.t.sina.com.cn/statuses/comment.json";
                    string text = "p评论测试"+a;
                    try
                    {
                        string result = httpRequest.Request(url, "comment=" + HttpUtility.UrlEncode(text) + "&id=" + ID + "&without_mention=0").ToString();
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    }
                    finally
                    {

                    }
                }
            }

        }

        protected void linkClear_Click(object sender, EventArgs e)
        {

        }
        //数据处理
        protected void rptWeiboList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
              
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                long ID = Convert.ToInt64(((HtmlInputHidden)e.Item.FindControl("hfID")).Value);
               StatusCount statusCount=GetStatusCount(ID.ToString());
                Panel retweete = ((Panel)e.Item.FindControl("retweete"));
                Label retweeteContent = ((Label)e.Item.FindControl("lblRetweeted"));

                Label commentCount = ((Label)e.Item.FindControl("lblCommnetCount"));
                Label rtCount =((Label)e.Item.FindControl("lblRTCount"));
                if (statusCount==null)
                {
                    rtCount.Text = "转发了0条";
                    commentCount.Text = "评论了0条";
                }
                else
                {
                    rtCount.Text = "转发了"+statusCount.rt+"条";
                   commentCount.Text = "评论了"+statusCount.comments+"条";
                }

                if(rdoOrg.Checked)
                {
                    retweete.Visible = false;
                }
                if (retweeteContent.Text.Trim().ToString()=="")
                {
                    retweete.Visible = false;
                }
             
            }
        }
    }
}
